package com.xu.service.impl.center;

import com.github.pagehelper.PageHelper;
import com.xu.enums.YesOrNo;
import com.xu.mapper.ItemsCommentsMapperCustom;
import com.xu.mapper.OrderItemsMapper;
import com.xu.mapper.OrderStatusMapper;
import com.xu.mapper.OrdersMapper;
import com.xu.pojo.OrderItems;
import com.xu.pojo.OrderStatus;
import com.xu.pojo.Orders;
import com.xu.pojo.bo.center.OrderItemsCommentBO;
import com.xu.pojo.vo.MyCommentVO;
import com.xu.service.center.MyCommentsService;
import com.xu.utils.PagedGridResult;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author anan
 * @create 2022-03-07 20:57
 */
@Service
public class MyCommentsServiceImpl extends BaseService implements MyCommentsService {
    @Autowired
    private OrderItemsMapper orderItemsMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private ItemsCommentsMapperCustom itemsCommentsMapperCustom;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderStatusMapper orderStatusMapper;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<OrderItems> queryPendingComment(String orderId) {
        OrderItems orderItems = new OrderItems();
        orderItems.setOrderId(orderId);
        return orderItemsMapper.select(orderItems);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveComments(String orderId, String userId, List<OrderItemsCommentBO> commentList) {
        // 1、保存评价 items_comments
        for(OrderItemsCommentBO oic : commentList){
            oic.setCommentId(sid.nextShort());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("commentList", commentList);
        itemsCommentsMapperCustom.saveComments(map);
        // 2、修改订单表改已评价
        Orders order = new Orders();
        order.setId(orderId);
        order.setIsComment(YesOrNo.Yes.type);
        ordersMapper.updateByPrimaryKeySelective(order);
        // 3、修改订单状态表的留言时间 order_status

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCommentTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(orderStatus);
    }

    @Override
    public PagedGridResult queryMyComments(String userId, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        PageHelper.startPage(page, pageSize);
        List<MyCommentVO> list = itemsCommentsMapperCustom.queryMyComments(map);
        PagedGridResult res = setterPageGrid(list, page);
        return res;

    }
}
